package com.hsxc.cdz.controller.consoleController;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsxc.cdz.base.bean.Address;
import com.hsxc.cdz.base.bean.ConsoleUser;
import com.hsxc.cdz.base.bean.Station;
import com.hsxc.cdz.base.util.CommonUtils;
import com.hsxc.cdz.base.util.TimeFormatter;
import com.hsxc.cdz.mgmt.station.StationManager;
import net.sf.json.JSONObject;

/**
 * @author 陈钊
 * @version 创建时间：2016年6月1日 下午4:30:38 类说明：
 */
@Controller
@RequestMapping("/api")
public class StationController {
	protected static Logger logger = LoggerFactory.getLogger(StationController.class);
	// ==============================================================================================================
	// 管理充电站
	@Autowired
	StationManager stationManager;

	// =================================================================================================================
	@RequestMapping(value = "/stations", method = RequestMethod.GET)
	@ResponseBody
	public Object getCDZhanByRoleName(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			HttpSession httpSession) {
		Station station = new Station();
		List<Station> cdzhans = new ArrayList<>();
		List<Station> cdzhans_time = null;
		TimeFormatter timeFormatter = new TimeFormatter();
		JSONObject jsonObject = new JSONObject();
		Subject user = SecurityUtils.getSubject();
		jsonObject.put("success", true);
		try {
			httpServletRequest.setCharacterEncoding("utf-8");
			httpServletResponse.setCharacterEncoding("UTF-8");
			String pro = httpServletRequest.getParameter("province");
			String city = httpServletRequest.getParameter("city");
			String county = httpServletRequest.getParameter("district");
			logger.debug("请求Station" + pro + city + county);
			jsonObject.put("success", true);
			Address address = new Address();
			address.setProvince(pro);
			address.setCity(city);
			address.setCounty(county);
			ConsoleUser consoleUser = (ConsoleUser) httpSession.getAttribute("conuser");
			logger.debug("consoleUser的姓名获取" + consoleUser.getId());
			logger.debug("consoleUser的角色获取" + consoleUser.getRole());
			if (user.hasRole("vendor") || user.hasRole("operator") || user.hasRole("stationAdmin")
					|| user.hasRole("opDeviceManager")) {
				cdzhans = stationManager.getCDZhanByRoleName(address, consoleUser.getUser_name(),
						consoleUser.getOperatorNO(), consoleUser.getRole());
				logger.debug(cdzhans.toString());
			}
			if (user.hasRole("virtualOperator")) {
				cdzhans = stationManager.getCDZhanByRoleName(address, null, consoleUser.getOperatorNO(),
						consoleUser.getRole());
				logger.debug(cdzhans.toString());
			}

			if (!cdzhans.isEmpty()) {
				cdzhans_time = new ArrayList<>();
				for (Iterator<Station> iterator = cdzhans.iterator(); iterator.hasNext();) {
					Station cdZhan = iterator.next();
					cdZhan.setRegTime(TimeFormatter.getTime(cdZhan.getRegTime()));
					cdZhan.setLogoutTime(TimeFormatter.getTime(cdZhan.getLogoutTime()));
					cdzhans_time.add(cdZhan);
				}
				jsonObject.put("data", cdzhans_time);
			} else {
				jsonObject.put("data", new ArrayList<>());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		ObjectMapper om = new ObjectMapper();
		try {
			om.writeValueAsString(jsonObject);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		logger.debug(jsonObject.toString());
		return jsonObject;
	}

	// ===================================================================================================================
	// 插入充电站
	@RequestMapping(value = "/stations", method = RequestMethod.POST)
	@ResponseBody
	public Object insertStation(@RequestBody String json, HttpSession httpSession) {
		Station station = new Station();
		JSONObject result = new JSONObject();
		result.put("success", true);
		try {
			org.json.JSONObject jsonObject = new org.json.JSONObject(json);
			Subject user = SecurityUtils.getSubject();
			ConsoleUser consoleUser = (ConsoleUser) httpSession.getAttribute("conuser");
			if (user.hasRole("vendor") || user.hasRole("operator")) {
				station.setOperatorNO(consoleUser.getOperatorNO());
				logger.debug("====================" + consoleUser.getOperatorNO() + "==============================");
			}
			String sno = CommonUtils.getTID();
			while (stationManager.selStationByNO(sno) != null) {
				sno = CommonUtils.getTID();
			}
			station.setStationNO(CommonUtils.getTID());
			station.setName(jsonObject.getString("name"));
			station.setMgrName(jsonObject.getString("mgrName"));
			String province = jsonObject.getString("province");
			String city = jsonObject.getString("city");
			String county = jsonObject.getString("county");
			String street = jsonObject.getString("street");
			StringBuilder s = new StringBuilder();
			s.append(province);
			s.append(city);
			s.append(county);
			s.append(street);
			station.setAddress(s.toString());
			station.setProvince(province);
			station.setCity(city);
			station.setCounty(county);
			station.setStreet(street);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			station.setRegTime(sdf.format(new Date()));

		} catch (Exception e) {
			result.put("added", false);
			result.put("errcode", 1);
			result.put("message", "数据解析失败");
			logger.info("message:" + "数据解析失败");
		}

		if (stationManager.selStation(station.getName()) != null) {
			result.put("added", false);
			result.put("errcode", 3);
			result.put("message", "名称已存在");
			logger.info("message:" + "名称已存在");
		} else {
			int i = stationManager.addStation(station);
			if (i <= 0) {
				result.put("added", false);
				result.put("errcode", 4);
				result.put("message", "充电站新建失败");
				logger.info("message:" + "充电站新建失败");
			}
			result.put("added", true);
			result.put("errcode", 0);
			result.put("message", "充电站新建成功");
			logger.info("message:" + "充电站新建成功");
		}
		return result;
	}

	// =============================================================================================================
	// 通过充电桩编号查询充电站
	@RequestMapping(value = "/stationpileno/{pileNO}", method = RequestMethod.GET)
	@ResponseBody
	public Object selectStationByPileNO(@PathVariable("pileNO") String pileNO) {
		JSONObject jsonObject = new JSONObject();
		if (pileNO == null) {
			jsonObject.put("success", false);
		} else {
			jsonObject.put("success", true);
			Station station = stationManager.selStationByPileNO(pileNO);
			JSONObject jsonObjectreturn = new JSONObject();
			jsonObjectreturn.put("province", station.getProvince());
			jsonObjectreturn.put("city", station.getCity());
			jsonObjectreturn.put("county", station.getCounty());
			jsonObjectreturn.put("name", station.getName());
			jsonObjectreturn.put("stationNO", station.getStationNO());
			jsonObject.put("data", jsonObjectreturn);
		}
		return jsonObject;
	}

	/**
	 * 更新充电站
	 * 
	 * @return
	 */
	@RequestMapping(value = "/stations", method = RequestMethod.PUT)
	@ResponseBody
	public Object updateStation(@RequestBody String data) {
		org.json.JSONObject json = null;
		JSONObject result = new JSONObject();
		result.put("success", true);
		int i = 0;
		try {
			json = new org.json.JSONObject(data);

		} catch (JSONException e) {
			result.put("added", false);
			result.put("errcode", 1);
			result.put("message", "json数据格式出错");
			return result;
		}
		try {
			String name = json.getString("name");
			String mgrName = json.getString("mgrName");
			String province = json.getString("province");
			String city = json.getString("city");
			String county = json.getString("county");
			String street = json.getString("street");
			Station station = new Station();
			station.setName(name);
			station.setMgrName(mgrName);
			station.setProvince(province);
			station.setCity(city);
			station.setCounty(county);
			station.setStreet(street);
			StringBuilder s = new StringBuilder();
			s.append(province);
			s.append(city);
			s.append(county);
			s.append(street);
			station.setAddress(s.toString());
			i = stationManager.updateStation(station);
		} catch (JSONException e) {
			result.put("added", false);
			result.put("errcode", 2);
			result.put("message", "数据解析失败");
			return result;
		} catch (Exception e) {
			result.put("added", false);
			result.put("errcode", 3);
			result.put("message", "服务器异常");
			return result;
		}

		logger.info("解析成功" + i);
		if (i == 0) {
			result.put("added", false);
			result.put("errcode", 4);
			result.put("message", "找不到该站");
			return result;
		}
		result.put("added", true);
		return result;
	}

	@RequestMapping(value = "/stations/{stationNO}", method = RequestMethod.DELETE)
	@ResponseBody
	public Object deleteStation(@PathVariable("stationNO") String stationNO) {
		logger.info("ENTER CONTROLLER OF DELETE STATION");
		logger.info("STATIONNO" + stationNO);
		JSONObject json = new JSONObject();
		json.put("success", true);
		if (stationNO == null) {
			json.put("added", false);
			json.put("errcode", 1);
			json.put("message", "站数据有误");
			return json;
		}

		int i = stationManager.delStation(stationNO);
		if (i == 0) {
			json.put("added", false);
			json.put("errcode", 2);
			json.put("message", "不存在该站");
			return json;
		}
		json.put("added", true);
		return json;
	}

}
